package com.ailot.cloud.base.security.config;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.Mode;
import cn.hutool.crypto.Padding;
import cn.hutool.crypto.symmetric.AES;
import com.ailot.cloud.base.common.constants.SecurityConstant;
import com.ailot.cloud.base.security.handler.*;
import com.ailot.cloud.base.security.properties.PermitUrlProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter;
import org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatcher;

import javax.annotation.PostConstruct;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@EnableWebSecurity
@EnableConfigurationProperties({PermitUrlProperties.class})
public class WebSecurityConfigurer {


    private final JwtEncoder jwtEncoder;
    private PermitUrlProperties permitUrlProperties;
    private List<AntPathRequestMatcher> antPathRequestMatcherList;

    public WebSecurityConfigurer(JwtEncoder jwtEncoder, PermitUrlProperties permitUrlProperties) {
        this.jwtEncoder = jwtEncoder;
        this.permitUrlProperties = permitUrlProperties;
    }

    @PostConstruct
    public void antPathMatcherList() {
        this.antPathRequestMatcherList = Optional.ofNullable(permitUrlProperties.getUrls()).orElse(new ArrayList<>()).stream().map(AntPathRequestMatcher::new).collect(Collectors.toList());
    }

    private final RequestMatcher PERMIT_ALL_REQUEST = (req) ->
            // 并且不包含token信息
            req.getHeader(HttpHeaders.AUTHORIZATION) == null &&
                    // 符合任意规则
                    this.antPathRequestMatcherList.stream().anyMatch(m -> m.matches(req));

    /**
     * 资源服务权限配置
     *
     * @param http
     * @return
     * @throws Exception
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return
                http
                        .authorizeRequests()
                        // 白名单不拦截
                        .requestMatchers(PERMIT_ALL_REQUEST)
                        .permitAll()
                        .anyRequest().authenticated()
                        .and()
                        .cors(cors -> cors.disable())
                        .csrf(csrf -> csrf.disable())
                        .formLogin()
                        .successHandler(new JwtAuthenticationSuccessHandler(jwtEncoder))
                        .failureHandler(new JwtAuthenticationFailureHandler())
                        .and()
                        .logout(logout -> logout.logoutSuccessHandler(new JwtLogoutSuccessHandler()))
                        .oauth2ResourceServer(oauth2ResourceServer -> oauth2ResourceServer
                                .jwt()
                                .jwtAuthenticationConverter(c -> {
                                    JwtGrantedAuthoritiesConverter jwtGrantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
                                    jwtGrantedAuthoritiesConverter.setAuthoritiesClaimName(SecurityConstant.AUTHORITIES);
                                    jwtGrantedAuthoritiesConverter.setAuthorityPrefix("");
                                    JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
                                    jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(jwtGrantedAuthoritiesConverter);
                                    return jwtAuthenticationConverter.convert(c);
                                })
                        )
                        //禁用session，JWT校验不需要session
                        .sessionManagement((session) -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                        .exceptionHandling(exception -> exception
                                //未授权异常
                                .accessDeniedHandler(new JwtAccessDeniedHandler())
                                .authenticationEntryPoint(new JwtAuthenticationEntryPoint())
                        ).build();


    }


    /**
     * 账号密码的加密方式
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
//        return new BCryptPasswordEncoder();
        return new BCryptPasswordEncoder() {
            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                /*
                 * 注意有提前加密
                 */
                return super.matches(decryptAES(rawPassword).trim(), encodedPassword);
            }
        };
    }

    private static String decryptAES(CharSequence password) {
        AES aes = new AES(Mode.CBC, Padding.NoPadding, new SecretKeySpec(SecurityConstant.FRONTEND_KEY.getBytes(), "AES"), new IvParameterSpec(SecurityConstant.FRONTEND_KEY.getBytes()));
        byte[] result = aes.decrypt(Base64.decode(password.toString().getBytes(StandardCharsets.UTF_8)));
        return new String(result, StandardCharsets.UTF_8);
    }
}
